<?php
// +----------------------------------------------------------------------
// |     【DealMain】Service服务类
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\common\service;

use think\facade\Request;
use app\common\model\DealMain as M;
use app\common\model\DealInfo as INFO_M;
use app\common\service\DealInfo as INFO_S;
use app\common\validate\DealMain as V;
use app\admin\controller\deal\Main as DEAL_C;
use app\common\service\BillMain as BILL_S;
use app\common\model\SystemConfig as CONFIG;

class DealMain{
    // 添加
    public static function goAdd($data,$callback=false){
        //验证
        $validate = new V;
        if(!$validate->scene('add')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
		
        try {
			$data=self::dataFormat($data,'add');
            $model=M::create($data['data']);
			return ['model'=>$data['data'],'info'=>$data['info'],'id'=>$model['id']];
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }
    
    // 编辑
    public static function goEdit($data,$id){
    	$where = is_array($id) ? $id : ['id'=>$id];
        //验证
        $validate = new V;
        // if(!$validate->scene('edit')->check($data))
        // return ['msg'=>$validate->getError(),'code'=>201];
        try {
			$data=self::dataFormat($data,'edit');
             M::update($data['data'],$where);
			 return ['model'=>$data['data'],'info'=>$data['info']];
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 状态
    public static function goStatus($data,$id){
        $model = is_array($id) ? M::where($id)->find() : M::find($id);
        if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
        try{
            $model->save($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 删除
    public static function goRemove($id,$uuid=0){
		$model = is_array($id) ? M::where($id)->find() : M::find($id);
		$cusid = $model['cusid'];
        if ($model->isEmpty()) return ['msg'=>'数据不存在','code'=>201];
        try{
           $model->delete();
		   INFO_S::goRemove($id,true);
		   
		   DEAL_C::upcustomer($cusid,$uuid);				//更新用户销售情况
		   BILL_S::up_bill($id,$uuid);					//更新收支
		   
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 批量删除
    public static function goBatchRemove($ids,$uuid=0){
        if (!is_array($ids)) return ['msg'=>'数据不存在','code'=>201];
		$model = M::where([['id','in',$ids],['uuid','=',$uuid]])->select();
        try{
            $model->delete();
			INFO_S::goBatchRemove($ids,true);
			
			DEAL_C::upcustomer($ids,$uuid);				//更新用户销售情况
			BILL_S::up_bill($ids,$uuid);				//更新收支
			
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 获取列表
    public static function goRecycle($where = []){
        if (Request::isPost()){
            $ids = Request::param('ids');
            if (!is_array($ids)) return ['msg'=>'参数错误','code'=>'201'];
            try{
                if(Request::param('type')){
                    $data = M::onlyTrashed()->whereIn('id', $ids)->select();
                    foreach($data as $k){
                        $k->restore();
                    }
					// 恢复子订单
					$data2 = INFO_M::onlyTrashed()->whereIn('did', $ids)->select();
					foreach($data2 as $k2){
					    $k2->restore();
					}
                }else{
                    M::destroy($ids,true);
					// 删除子订单（真实）
					INFO_M::destroy(function($query){
						$query->where('did',$ids);
					},true);
					
                }
            }catch (\Exception $e){
                return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
            }
            return ['msg'=>'操作成功'];
        }
        //按用户名
        
        $limit = I('get.limit/d');
        
        $list = M::onlyTrashed()->where($where)->paginate($limit);
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }
	
	//修改某个参数
	public static function setFieldValue($data,$where=[]){
		if(empty($where)){
			$model =  M::find($data['id']);
		}else{
			$model = M::where($where)->find();
		}
		if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
		try{
		    $model->save([
		        $data['field'] => $data['value'],
		    ]);
			return ['msg'=>'操作成功'];
		}catch (\Exception $e){
		    return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
		}
	}
	
	// 预处理添加和修改的数据
	public static function dataFormat($data,$type='add'){
		if($type == 'add'){					//添加时才处理
			$data['number']=date('ymdHis').rand(100,999);
			$data['get']=0;
			$data['addedname']='';
			$data['added']=0;
			$data['print']=0;
			$data['update_time']=time();
			$data['refundtime']='';
			$data['refundtxt']='';
			//	计算手续费
			$data['poundage']=self::deal_poundage($data['total'],$data['paytype']);
		}else if($type == 'edit'){			//修改时才处理
			//	计算手续费
			$data['update_time']=time();
			$data['poundage']=self::deal_poundage($data['total'],$data['paytype']);
		}
		// 无论修改还是添加都处理
		$data['create_time']=strtotime($data['create_time']);
		$data['year']=date('Y',$data['create_time']);
		$data['month']=date('m',$data['create_time']);
		$data['day']=date('d',$data['create_time']);
		$info=$data['info'];
		unset($data['info']);
		return ['data'=>$data,'info'=>$info];
	}
	
	// 计算手续费
	protected static function deal_poundage($money,$paytype){
		//计算手续费
		if($paytype=='诚E赊'){
			return price_one($money*0.005);
		}else if($paytype=='扫呗支付'){
			$lcsw=CONFIG::get('api.lcsw');
			return price_one($money*$lcsw['poundage']??0.0025);
		}else{
			return 0;
		}
	}
}
